const {
	reqGet,
	reqPost,
} = require('@utils/request')
const {
	$U_UserInfo,
} = require('@utils/storage')
const {
	setFormEdit,
	setBtnEdit,
	randomId,
} = require('./api-utils')
const {
	addModuleHistory,
	addApiHistory,
	delNodeHistory,
	apiDetailModifyHistory,
	nameModifyHistory,
} = require('./api-utils-history-2x')
const {
	loadProjectData,
	loadAPIDetail,
} = require('./api-data-2x')

module.exports = {
	/**
	 * 右键菜单:添加模块
	 * @param {[type]} apiComp [description]
	 */
	addModuleMethod(e) {
		let {
			store,
			treeComp,
			treeMenuComp,
		} = this
		if (!store.isLock)
			return false
		let _currentTreeNode = store._currentTreeNode
		if (!_currentTreeNode || !_currentTreeNode.target)
			return false
		let editProjectData = store.editProjectData
		let moduleId = `module-${randomId()}`
		let apiId = `api-${randomId()}`
		treeComp.tree('append', {
			data: [{
				id: moduleId,
				text: `新建模块`,
				state: 'open',
				children: [{
					id: apiId,
					text: '新建接口',
				}]
			}]
		});
		let api = {
			id: apiId,
			name: '新建接口',
			intro: "",
			method: "GET",
			path: "",
			contentType: "application/x-www-form-urlencoded",
			requestParameterList: [],
			responseParameterList: [],
		}
		let module = {
			id: moduleId,
			name: `新建模块`,
		}
		editProjectData.apis[apiId] = api;
		editProjectData.modules[moduleId] = module;
		// 选中当前节点，保存上一个节点数据
		loadAPIDetailMethod.call(this, api);
		addModuleHistory.call(this, apiId, moduleId)
	},

	/**
	 * 添加子模块
	 * @param {[type]} e [description]
	 */
	addChildModuleMethod(e) {
		let {
			store,
			treeComp,
			treeMenuComp,
		} = this
		if (!store.isLock)
			return false
		let _currentTreeNode = store._currentTreeNode
		if (!_currentTreeNode || !_currentTreeNode.target)
			return false
		let editProjectData = store.editProjectData
		let moduleId = `module-${randomId()}`
		let apiId = `api-${randomId()}`
		treeComp.tree('append', {
			parent: _currentTreeNode.target,
			data: [{
				id: moduleId,
				text: `新建子模块`,
				state: 'open',
				children: [{
					id: apiId,
					text: '新建接口',
				}]
			}],
		});
		let api = {
			id: apiId,
			name: '新建接口',
			intro: "",
			method: "GET",
			path: "",
			contentType: "application/x-www-form-urlencoded",
			requestParameterList: [],
			responseParameterList: []
		}
		let module = {
			id: moduleId,
			name: `新建子模块`,
		}
		editProjectData.apis[apiId] = api;
		editProjectData.modules[moduleId] = module;
		// 选中当前节点，保存上一个节点数据
		loadAPIDetailMethod.call(this, api);
		addModuleHistory.call(this, apiId, moduleId, true, _currentTreeNode.id)
	},

	/**
	 * 右键菜单:添加接口
	 * @param {[type]} apiComp [description]
	 */
	addAPIMethod(e) {
		let {
			store,
			treeComp,
			treeMenuComp,
		} = this
		if (!store.isLock)
			return false
		let _currentTreeNode = store._currentTreeNode
		if (!_currentTreeNode || !_currentTreeNode.target)
			return false
		let editProjectData = store.editProjectData
		let apiId = `api-${randomId()}`
		treeComp.tree('append', {
			parent: _currentTreeNode.target,
			data: [{
				id: apiId,
				text: '新建接口',
			}]
		});
		let api = {
			id: apiId,
			name: '新建接口',
			intro: "",
			method: "GET",
			path: "",
			contentType: "application/x-www-form-urlencoded",
			requestParameterList: '',
			responseParameterList: ''
		}
		editProjectData.apis[apiId] = api;
		// 选中当前节点，保存上一个节点数据
		loadAPIDetailMethod.call(this, api);
		addApiHistory.call(this, apiId, _currentTreeNode.id)
	},

	/**
	 * 删除模块/接口树节点
	 * @param  {[type]} e [description]
	 * @return {[type]}   [description]
	 */
	delTreeMethod(e) {
		let {
			store,
			treeComp,
		} = this
		if (!store.isLock)
			return false;
		let _currentTreeNode = store._currentTreeNode
		if (!_currentTreeNode || !_currentTreeNode.target)
			return false
		let apiComp = this
		$.messager.confirm({
			title: '提示',
			msg: '删除节点后不可恢复，确认删除？',
			fn(r) {
				if (r) {
					let nodeId = _currentTreeNode.id
					let editProjectData = store.editProjectData
					store._currentCheckApiDetail = null
					deleteApi(apiComp, _currentTreeNode, editProjectData);
					treeComp.tree('remove', _currentTreeNode.target)
					loadAPIDetail(apiComp)
				}
			}
		})
	},

	/**
	 * 右键点击显示树结构模块菜单
	 * 默认模块、默认接口不可以删除
	 * @param  {[type]} e    [description]
	 * @param  {[type]} node [description]
	 * @return {[type]}      [description]
	 */
	showTreeMenu(e, node) {
		e.preventDefault()
		console.log('node', node)
		let {
			store,
			treeComp,
			treeMenuComp,
		} = this
		if (!store.isLock)
			return false;
		let parentNode = treeComp.tree('getParent', node.target)
		let item1 = treeMenuComp.menu('findItem', '添加模块')
		let item2 = treeMenuComp.menu('findItem', '添加接口')
		let item3 = treeMenuComp.menu('findItem', '删除')
		let item4 = treeMenuComp.menu('findItem', '添加子模块')
		let item1Show = !parentNode && node.children && node.children[0] ? 'showItem' : 'hideItem'
		let opts = node.children && node.children[0] ? 'showItem' : 'hideItem'
		let delOps = /(api|module)-0{8}$/.test(node.id) ? 'hideItem' : 'showItem'
		treeMenuComp.menu(item1Show, item1.target)
		treeMenuComp.menu(opts, item2.target)
		treeMenuComp.menu(delOps, item3.target)
		treeMenuComp.menu(opts, item4.target)
		if (opts == 'hideItem' && delOps == 'hideItem')
			return false
		treeMenuComp.menu('show', {
			left: e.pageX,
			top: e.pageY,
		})
		store._currentTreeNode = node
		if (!node.children || !node.children[0]) {
			store._currentCheckApiDetail = store.editProjectData.apis[node.id]
			loadAPIDetail(this, node)
		}
	},

	// 加载某个api详细信息
	loadAPIDetailMethod(node) {
		let {
			store,
			treeComp,
		} = this
		if (!store.isLock && node.children && node.children[0]) {
			if (node.state == 'open')
				treeComp.tree('collapse', node.target)
			else
				treeComp.tree('expand', node.target)
		}
		loadAPIDetailMethod.call(this, node)
	},

	/**
	 * 模块/接口名修改,同步editProjectData中信息
	 * @param {[type]} node [description]
	 */
	setModuleNameMethod(node) {
		if (typeof node.text == 'undefined')
			return false
		let nodeId = node.id
		let apis = this.store.editProjectData.apis
		let modules = this.store.editProjectData.modules
		this.store._currentTreeNode = null
		let oldName = this.store.tmpNodeName
		if (oldName == node.text)
			return false
		let type = 'modules'
		let moduleId = ''
		if (apis[nodeId]) {
			this.formName.textbox('setValue', node.text)
			apis[nodeId].name = node.text
			type = 'apis'
			moduleId = this.treeComp.tree('getParent', node.target).id
		}
		if (modules[nodeId]) {
			let parentNode = this.treeComp.tree('getParent', node.target)
			modules[nodeId].name = node.text
			moduleId = parentNode && parentNode.id || ''
		}
		nameModifyHistory.call(this, type, nodeId, node.text, moduleId)
	},
}

function loadAPIDetailMethod(node) {
	let {
		store,
		reqParamsComp,
		resParamsComp,
		formIntro,
		formMethod,
		formPath,
		formContentType,
		treeMenuComp,
		treeComp,
	} = this
	if (store.beginEditName && store._currentTreeNode) {
		treeComp.tree('endEdit', store._currentTreeNode.target)
		store.beginEditName = false
	}
	if (node.children && node.children.length > 0)
		return false;
	// 保存上一个接口详细参数
	if (store.isLock && store._currentEditApiDetail) {
		let apiId = store._currentEditApiDetail.id
		let apiDetail = store.editProjectData.apis[apiId];
		apiDetail.intro = formIntro.textbox('getText');
		apiDetail.method = formMethod.textbox('getText');
		apiDetail.path = formPath.textbox('getText');
		apiDetail.contentType = formContentType.textbox('getText');
		apiDetail.requestParameterList = reqParamsComp.treegrid('getData');
		apiDetail.responseParameterList = resParamsComp.treegrid('getData');
	}
	store._currentCheckApiDetail = store.editProjectData.apis[node.id]
	loadAPIDetail(this)
}

/**
 * 递归删除模块和所有api及子模块
 * @param  {[type]} apiComp         [description]
 * @param  {[type]} node            [description]
 * @param  {[type]} editProjectData [description]
 * @return {[type]}                 [description]
 */
function deleteApi(apiComp, node, editProjectData) {
	if (!node.target)
		node = apiComp.treeComp.tree('find', node.id)
	if (!node)
		return false
	let parentNode = apiComp.treeComp.tree('getParent', node.target)
	if (!Array.isArray(node.children) || !node.children[0]) {
		delete editProjectData.apis[node.id]
		delNodeHistory.call(apiComp, {
			id: node.id,
			type: 'apis',
			moduleId: parentNode && parentNode.id || "",
		})
	} else {
		delete editProjectData.modules[node.id]
		delNodeHistory.call(apiComp, {
			id: node.id,
			type: 'modules',
			moduleId: parentNode && parentNode.id || "",
		})
		for (let i = 0; i < node.children.length; i++) {
			let cnode = node.children[i]
			deleteApi(apiComp, cnode, editProjectData);
		}
	}
}